﻿/**
* CRL
*/
using CRL.Data.DBAccess;
using System;
//using System.Data;
using System.Linq.Expressions;
using System.Reflection;

namespace CRL.Data
{
    public class Base
    {
        //static internal bool UseEmitCreater = true;
        internal static Expression<Func<TModel, bool>> GetQueryIdExpression<TModel>(object id)
        {
            var type = typeof(TModel);
            var table = TypeCache.GetTable(type);
            if (table.PrimaryKey.PropertyType != id.GetType())
            {
                throw new Exception("参数类型与主键类型定义不一致");
            }
            var parameter = Expression.Parameter(type, "b");
            //创建常数 
            var constant = Expression.Constant(id);
            MemberExpression member = Expression.PropertyOrField(parameter, table.PrimaryKey.MemberName);
            var body = Expression.Equal(member, constant);
            //获取Lambda表达式
            var lambda = Expression.Lambda<Func<TModel, Boolean>>(body, parameter);
            //var pr = lambda.Compile();
            return lambda;
        }

        /// <summary>
        /// 获取当前版本
        /// </summary>
        /// <returns></returns>
        public static string GetVersion()
        {
            var assembly = System.Reflection.Assembly.GetExecutingAssembly().GetName();
            return assembly.Version.ToString();
        }
        //internal static string FormatFieldPrefix(DBAdapter.DBAdapterBase dBAdapter, Type type, string fieldName)
        //{
        //    return "{" + type.FullName + "}" + dBAdapter.KeyWordFormat(fieldName);
        //}
        #region callContext
        internal const string UseCRLContextFlagName = "__CRLContextFlagName";
        internal const string CRLContextName = "__TransDbContext";
        //internal const string AllDBExtendName = "__AllDBExtend";
        //internal const string SQLRunningtimeName = "__SQLRunningtime";
        internal const string UseTransactionScopeName = "__TransactionScopeName";
        internal const string ContextPathName = "__ContextPathName";
        #endregion
        internal static DataBaseArchitecture GetDataBaseArchitecture(DBType dbType)
        {
            if (dbType == DBType.MongoDB || dbType == DBType.ES)
            {
                return DataBaseArchitecture.NotRelation;
            }
            return DataBaseArchitecture.Relation;
        }
        internal static bool CheckIfAnonymousType(Type type)
        {
            if (type == null)
                throw new ArgumentNullException("type");

            return type.IsGenericType && type.Name.Contains("AnonymousType")
                && (type.Name.StartsWith("<>"))
                && (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
        }
		public static void ClearCache()
		{
			TypeCache.typeCache.Clear();
			TypeCache.ModelKeyCache.Clear();
            LambdaQuery.LambdaQueryBase.queryFieldCache.Clear();
		}
	}
}
